<?php

namespace app\admin\middleware;

use think\Request;
use think\Response;
use think\facade\Session;
use app\admin\model\Admin as AdminModel;
use Closure;
use ReflectionClass;

class CheckLogin
{
    public function handle(Request $request, Closure $next): Response
    {
        $controller = $request->controller();
        if (empty($controller)) return $next($request);
        $url = url('index/login')->build();
        if (str_contains($controller, '.')) $controller = str_replace('.', '\\', $controller);
        $action          = $request->action();
        $controllerClass = 'app\\admin\\controller\\' . $controller;
        $classObj        = new ReflectionClass($controllerClass);
        $properties      = $classObj->getDefaultProperties();

        // 不需要验证登录的方法
        $noNeedLogin = $properties['noNeedLogin'] ?? ['*'];
        if (in_array('*', $noNeedLogin) || in_array($action, $noNeedLogin)) {
            return $next($request);
        }

        $admin_id = Session::get("admin.id");
        if (!$admin_id) {
            // 未登录
            return redirect($url);
        }

        // 判断管理员ID是否存在
        $admin_info = AdminModel::find($admin_id);
        if (empty($admin_info)) {
            // 管理员不存在
            return redirect($url);
        }

        $request->adminInfo = $admin_info;

        return $next($request);
    }
}